// BrowserForFolder.cpp: implementation of the BrowserForFolder class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "BrowserForFolder.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

BrowserForFolder::BrowserForFolder(CWnd* pParent, 
								   const CString& strDialogName, 
								   const CString& strStartPos)
{
	ASSERT(pParent);
	ASSERT(!strDialogName.IsEmpty());

	m_strDialogName = strDialogName;
	m_pParent = pParent;
	m_strStartPos = strStartPos;
	m_strPath = strStartPos;
	m_hWndEdit = NULL;
}

BrowserForFolder::~BrowserForFolder()
{

}

BOOL BrowserForFolder::DoModal()
{
	BROWSEINFO info;
	memset(&info, 0, sizeof(BROWSEINFO));

	info.lpfn = &BrowserForFolder::BrowseCallbackProc;
	info.hwndOwner = m_pParent->GetSafeHwnd();

	info.lpszTitle = m_strDialogName;
	info.ulFlags = BIF_EDITBOX|BIF_RETURNONLYFSDIRS|BIF_VALIDATE;
	info.lParam = (DWORD)this;

	BOOL bResult = SHGetPathFromIDList(SHBrowseForFolder(&info),m_strPath.GetBuffer(256));
	m_strPath.ReleaseBuffer();

	return bResult;
}

CString BrowserForFolder::GetStartPos()
{
	while(m_strStartPos.Right(1)==_T("\\")) 
		m_strStartPos.Delete(m_strStartPos.GetLength()-1,1);

	return m_strStartPos;
}

int CALLBACK BrowserForFolder::BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lParam,LPARAM lpData)
{
	BrowserForFolder* pFolder = (BrowserForFolder*)(lpData);
	ASSERT(pFolder);
	
	CString strDir;
	
	switch (uMsg)
	{
	case BFFM_INITIALIZED:
		{
			::SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (DWORD)pFolder->m_strStartPos.GetBuffer(0));
			pFolder->m_strStartPos.ReleaseBuffer();

			CRect rect;   
			HWND  hChild = GetWindow(hwnd, GW_CHILD);
			while (hChild) 
			{
				TCHAR szClass[256];
				GetClassName(hChild, szClass, 255);

				if (strcmp(szClass, "Edit") == 0)
				{
					pFolder->m_hWndEdit = hChild;
					SetWindowText(pFolder->m_hWndEdit, pFolder->m_strStartPos);
					break;
				}
				
				hChild = GetNextWindow(hChild, GW_HWNDNEXT);
			}
		}
		break;
		
	case BFFM_SELCHANGED:
		if(pFolder->m_hWndEdit)
		{
			if(::SHGetPathFromIDList((LPITEMIDLIST)lParam, strDir.GetBufferSetLength(MAX_PATH)))
			{
				SetWindowText(pFolder->m_hWndEdit, strDir);
			}
			else
			{
				SetWindowText(pFolder->m_hWndEdit, NULL);
				SendMessage(hwnd, BFFM_VALIDATEFAILED, 0, 0);
			}
			strDir.ReleaseBuffer();
		}
		break;
	default:
		break;
		
	}
	
	return 0;
}

